package top.yueyazhui.valid.exception;

import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.yueyazhui.valid.bean.Response;

import java.util.Objects;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Response exceptionHandle(Exception e) {
        Response result;
		if (e instanceof MethodArgumentNotValidException){
            result = Response.error("参数错误：" + Objects.requireNonNull(((MethodArgumentNotValidException) e).getBindingResult().getFieldError()).getDefaultMessage());
        } else {
			result = Response.error("服务器内部错误");
		}
        return result;
    }
}
